function total(){//获取总金额
	var t = 0;
	var list = $('input[type=checkbox]');
	for(var i=0;i<list.length;i++){
		var ck = list[i].checked;
		if(ck){
			var id = list[i].id.split('_')[1]
			if(i!=0){
				console.log($('#tprice_'+id).html());
				t+=parseFloat($('#tprice_'+id).html());
				
			}
		}
	}
	$('#totalMoney').html(t);
}
function checkChks(obj, cobj) {
    ZZHT.checkChks(obj, cobj);
    $(cobj).each(function () {
        id = $(this).val();
        if (obj.checked) {
            $(this).addClass('selected');
        } else {
            $(this).removeClass('selected');
        }
        var cid = $(this).find(".j-chk").val();
        if (cid != '') {
            ZZHT.changeCartGoods(cid, $('#buyNum_' + cid).val(), obj.checked ? 1 : 0);
            statCartMoney();
        }
    })
    total();
}
function statCartMoney() {
    var cartMoney = 0, goodsTotalPrice, id,cartScore = 0;
    $('.j-gchk').each(function () {
        id = $(this).val();
        goodsTotalPrice = parseFloat($(this).attr('mval')) * parseInt($('#buyNum_' + id).val());
        //goodsTotalScore = parseFloat($(this).attr('payScore')) * parseInt($('#buyNum_' + id).val());
        // if(goodsTotalScore > 0) {
        //     $('#tprice_' + id).html(goodsTotalPrice+'+'+goodsTotalScore+'积分');
        // } else {
        //     $('#tprice_' + id).html(goodsTotalPrice);
        // }
        if ($(this).prop('checked')) {
            cartMoney = cartMoney + goodsTotalPrice;
            cartScore = cartScore + goodsTotalScore;
        }
    });
    $('#totalMoney').html(cartMoney);
    if(cartScore > 0) {
        $('#totalScore').html('应付总积分：'+cartScore);
    } else {
        $('#totalScore').html('');
    }
    checkGoodsBuyStatus();
}
function checkGoodsBuyStatus() {
    var cartNum = 0, stockNum = 0, cartId = 0;
    $('.j-gchk').each(function () {
        cartId = $(this).val();
        cartNum = parseInt($('#buyNum_' + cartId).val(), 10);
        stockNum = parseInt($(this).attr('sval'), 10);
        ;
        if (stockNum < 0 || stockNum < cartNum) {
            if ($(this).prop('checked')) {
                $(this).parent().parent().css('border', '2px solid red');
            } else {
                $(this).parent().parent().css('border', '0px solid #eeeeee');
                $(this).parent().parent().css('border-bottom', '1px solid #eeeeee');
            }
            if (stockNum < 0) {
                $('#gchk_' + cartId).attr('allowbuy', 0);
                $('#err_' + cartId).css('color', 'red').html('库存不足');
            } else {
                $('#gchk_' + cartId).attr('allowbuy', 1);
                $('#err_' + cartId).css('color', 'red').html('购买量超过库存');
            }
        } else {
            $('#gchk_' + cartId).attr('allowbuy', 10);
            $(this).parent().parent().css('border', '0px solid #eeeeee');
            $(this).parent().parent().css('border-bottom', '1px solid #eeeeee');
            $('#err_' + cartId).html('');
        }
    });
}
function toSettlement() {
    var isChk = false;
    $('.j-gchk').each(function () {
        if ($(this).prop('checked')) isChk = true;
    });
    if (!isChk) {
        ZZHT.msg('请选择要结算的商品!', {icon: 1});
        return;
    }
    var msg = '';
    $('.j-gchk').each(function () {
        if ($(this).prop('checked')) {
            if ($(this).attr('allowbuy') == 0) {
                msg = '所选商品库存不足';
                return;
            } else if ($(this).attr('allowbuy') == 1) {
                msg = '所选商品购买量大于商品库存';
                return;
            }
        }
    })
    if (msg != '') {
        ZZHT.msg(msg, {icon: 2});
        return;
    }
    location.href = '../confirm/qrdd.html';
}

function addrBoxOver(t) {
    $(t).addClass('radio-box-hover');
    $(t).find('.operate-box').show();
}
function addrBoxOut(t) {
    $(t).removeClass('radio-box-hover');
    $(t).find('.operate-box').hide();
}

function setDeaultAddr(id) {
    $.post(ZZHT.U('home/useraddress/setDefault'), {id: id}, function (data) {
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            getAddressList();
            changeAddrId(id);
        }
    });
}


function changeAddrId(id) {
    $.post(ZZHT.U('home/useraddress/getById'), {id: id}, function (data) {
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            inEffect($('#addr-' + id), 1);
            $('#s_addressId').val(json.data.addressId);
            $('#s_areaId').val(json.data.areaId);
            ZZHT.setValues(json.data);
            getCartMoney(json.data.cityId);
        }
    })
}

function delAddr(id) {
    ZZHT.confirm({
        content: '您确定要删除该地址吗？', yes: function (index) {
            $.post(ZZHT.U('home/useraddress/del'), {id: id}, function (data, textStatus) {
                var json = ZZHT.toJson(data);
                if (json.status == 1) {
                    ZZHT.msg(json.msg, {icon: 1});
                    getAddressList();
                } else {
                    ZZHT.msg(json.msg, {icon: 2});
                }
            });
        }
    });
}

function getAddressList(obj) {
    var id = $('#s_addressId').val();
    var load = ZZHT.load({msg: '正在加载记录，请稍后...'});
    $.post(ZZHT.U('home/useraddress/listQuery'), {rnd: Math.random()}, function (data, textStatus) {
        layer.close(load);
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            if (json.data && json.data && json.data.length) {
                var html = [], tmp;
                for (var i = 0; i < json.data.length; i++) {
                    tmp = json.data[i];
                    var selected = (id == tmp.addressId) ? 'j-selected' : '';
                    html.push(
                        '<div class="ZZHT-frame1 ' + selected + '" onclick="javascript:changeAddrId(' + tmp.addressId + ')" id="addr-' + tmp.addressId + '" >' + tmp.userName + '<i></i></div>',
                        '<li class="radio-box" onmouseover="addrBoxOver(this)" onmouseout="addrBoxOut(this)">',
                        tmp.userName,
                        '&nbsp;&nbsp;',
                        tmp.areaName + tmp.userAddress,
                        '&nbsp;&nbsp;&nbsp;&nbsp;',
                        tmp.userPhone
                    )
                    if (tmp.isDefault == 1) {
                        html.push('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="j-default">默认地址</span>')
                    }
                    html.push('<div class="operate-box">');
                    if (tmp.isDefault != 1) {
                        html.push('<a href="javascript:;" onclick="setDeaultAddr(' + tmp.addressId + ')">设为默认地址</a>&nbsp;&nbsp;');
                    }
                    html.push('<a href="javascript:void(0)" onclick="javascript:toEditAddress(' + tmp.addressId + ',this,1,1)">编辑</a>&nbsp;&nbsp;');
                    if (json.data.length > 1) {
                        html.push('<a href="javascript:void(0)" onclick="javascript:delAddr(' + tmp.addressId + ',this)">删除</a></div>');
                    }
                    html.push('<div class="ZZHT-clear"></div>', '</li>');
                }
                html.push('<a style="color:#1c9eff" onclick="editAddress()" href="javascript:;">收起地址</a>');


                $('#addressList').html(html.join(''));
            } else {
                $('#addressList').empty();
            }
        } else {
            $('#addressList').empty();
        }
    })
}


function inEffect(obj, n) {
    $(obj).addClass('j-selected').siblings('.ZZHT-frame' + n).removeClass('j-selected');
}
function editAddress() {
    var isNoSelected = false;
    $('.j-areas').each(function () {
        isSelected = true;
        if ($(this).val() == '') {
            isNoSelected = true;
            return;
        }
    })
    if (isNoSelected) {
        ZZHT.msg('请选择完整收货地址！', {icon: 2});
        return;
    }
    var userPhone = $('#userPhone').val();
    var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
    if(userPhone == '' || !myreg.test(userPhone)){
        ZZHT.msg('请填写十一位的手机号', {icon: 2});
        return;
    }
    var load = ZZHT.load({msg: '正在提交数据，请稍后...'});
    var params = ZZHT.getParams('.j-eipt');
    params.areaId = ZZHT.ITGetAreaVal('j-areas');
    $.post(ZZHT.U('home/useraddress/' + ((params.addressId > 0) ? 'toEdit' : 'add')), params, function (data, textStatus) {
        layer.close(load);
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            layer.close(layerbox);
            $('.j-edit-box').hide();
            $('.j-list-box').hide();
            $('.j-show-box').show();
            if (params.addressId == 0) {
                $('#s_addressId').val(json.data.addressId);
            } else {
                $('#s_addressId').val(params.addressId);
            }
            var areaIds = ZZHT.ITGetAllAreaVals('area_0', 'j-areas');
            getCartMoney(areaIds[1]);
            var areaNames = [];
            $('.j-areas').each(function () {
                areaNames.push($('#' + $(this).attr('id') + ' option:selected').text());
            })
            $('#s_userName').html(params.userName + '<i></i>');
            $('#s_address').html(params.userName + '&nbsp;&nbsp;&nbsp;' + areaNames.join('') + '&nbsp;&nbsp;' + params.userAddress + '&nbsp;&nbsp;' + params.userPhone);
            if (params.isDefault == 1) {
                $('#isdefault').html('默认地址').addClass('j-default');
            } else {
                $('#isdefault').html('').removeClass('j-default');
            }
        } else {
            ZZHT.msg(json.msg, {icon: 2});
            return;
        }
    });
}
var layerbox;
function showEditAddressBox() {
    getAddressList();
    toEditAddress();
}
function emptyAddress(obj, n) {
    inEffect(obj, n);
    $('#addressForm')[0].reset();
    $('#s_addressId').val(0);
    $('#addressId').val(0);
    $("select[id^='area_0_']").remove();

    layerbox = layer.open({
        title: '用户地址',
        type: 1,
        area: ['600px', '360px'],
        content: $('.j-edit-box')
    });
}
function toEditAddress(id, obj, n, flag, type) {
    inEffect(obj, n);
    id = (id > 0) ? id : $('#s_addressId').val();
    $.post(ZZHT.U('home/useraddress/getById'), {id: id}, function (data, textStatus) {
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            if (flag) {
                layerbox = layer.open({
                    title: '用户地址',
                    type: 1,
                    area: ['800px', '360px'], //宽高
                    content: $('.j-edit-box')
                });
            }
            if (type != 1) {
                $('.j-list-box').show();
                $('.j-show-box').hide();
            }
            ZZHT.setValues(json.data);
            $('input[name="addrUserPhone"]').val(json.data.userPhone)
            $("select[id^='area_0_']").remove();
            if (id > 0) {
                var areaIdPath = json.data.areaIdPath.split("_");
                $('#area_0').val(areaIdPath[0]);
                var aopts = {id: 'area_0', val: areaIdPath[0], childIds: areaIdPath, className: 'j-areas'}
                ZZHT.ITSetAreas(aopts);
            }
        } else {
            ZZHT.msg(json.msg, {icon: 2});
        }
    });
}
function getCartMoney(areaId2) {
    var load = ZZHT.load({msg: '正在计算运费，请稍后...'});
    $.post(ZZHT.U('home/carts/getCartMoney'), {areaId2: areaId2, rnd: Math.random()}, function (data, textStatus) {
        layer.close(load);
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            var shopFreight = 0;
            for (var key in json.shops) {
                console.log(key);
                shopFreight = shopFreight + json.shops[key]['freight'];
                $("#deleverFee_" + key).html("￥" + json.shops[key]['freight']);
                $("#shop_totalFee_" + key).html("￥" + json.shops[key]['shopTotalMoney']);
            }
            $('#deliverMoney').html(shopFreight);
            $('#totalMoney').html(json.total);
        }
    });
}

function submitOrder() {
    var params = ZZHT.getParams('.j-ipt');
    var load = ZZHT.load({msg: '正在提交，请稍后...'});
    $.post(ZZHT.U('home/orders/submit'), params, function (data, textStatus) {
        layer.close(load);
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            ZZHT.msg(json.msg, {icon: 1}, function () {
                location.href = ZZHT.U('pay/Checkout/index', 'orderno=' + json.data + '&isBatch=1&scenecode=BUY_GOODS');
            });
        } else {
            ZZHT.msg(json.msg, {icon: 2});
        }
    });
}


ZZHT.showhide = function (t, str, obj) {
    var s = str.split(',');
    if (t) {
        for (var i = 0; i < s.length; i++) {
            $(s[i]).show();
        }
    } else {
        for (var i = 0; i < s.length; i++) {
            $(s[i]).hide();
        }
    }
    s = null;
    changeSelected(t, 'isInvoice', obj);
}
function changeSelected(n, index, obj) {
    $('#' + index).val(n);
    inEffect(obj, 2);
}


function getPayUrl() {
    var params = {};
    params.orderNo = $("#orderNo").val();
    params.isBatch = $("#isBatch").val();
    params.payCode = $.trim($("#payCode").val());
    if (params.payCode == "") {
        ZZHT.msg('请先选择支付方式', {icon: 5});
        return;
    }
    jQuery.post(ZZHT.U('home/' + params.payCode + '/get' + params.payCode + "URL"), params, function (data) {
        var json = ZZHT.toJson(data);
        if (json.status == 1) {
            if (params.payCode == "weixinpays") {
                location.href = json.url;
            } else {
                window.open(json.url);
            }
        } else {
            ZZHT.msg('您的订单已支付!', {icon: 5});
            setTimeout(function () {
                window.location = ZZHT.U('home/orders/waitReceive');
            }, 1500);
        }
    });
}